using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.LMZWorkSchedule;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_ViewModel.LMZWorkSchedule
{
    /// <summary>
    /// 报工质检详情页面的ViewModel
    /// </summary>
    public class WorkReportQualityDetailViewModel : BaseViewModel
    {
        private WorkReportQualityItem? _currentItem;
        private bool _canSave = true;
        private bool _isSaving = false;
        private bool _isLoadingPlans = false;
        private bool _isAllSelected = false;
        private readonly ApiService _apiService;
        private ObservableCollection<QualityInspectionPlan> _qualityInspectionPlans;

        /// <summary>
        /// 页面导航事件 - 用于通知主窗口切换页面
        /// </summary>
        public static event Action<string>? RequestNavigateToPage;

        public WorkReportQualityDetailViewModel()
        {
            // 初始化API服务
            _apiService = new ApiService();

            // 初始化集合
            _qualityInspectionPlans = new ObservableCollection<QualityInspectionPlan>();

            // 初始化命令
            BackCommand = CreateCommand(ExecuteBack);
            SaveCommand = CreateCommand(async () => await ExecuteSaveAsync(), () => CanSave && !IsSaving);
            SelectAllCommand = CreateCommand(ExecuteSelectAll);

            // 从MainWindowViewModel获取当前项目数据
            LoadCurrentItem();

            // 加载质检方案
            _ = LoadQualityInspectionPlansAsync();
        }

        /// <summary>
        /// 加载当前项目数据
        /// </summary>
        private void LoadCurrentItem()
        {
            if (WPF_MVVM_Test.MVVM_ViewModel.MainWindowViewModel.CurrentWorkReportQualityItem != null)
            {
                CurrentItem = WPF_MVVM_Test.MVVM_ViewModel.MainWindowViewModel.CurrentWorkReportQualityItem;
            }
        }

        /// <summary>
        /// 刷新当前项目数据（公共方法，供外部调用）
        /// </summary>
        public void RefreshCurrentItem()
        {
            LoadCurrentItem();
        }

        /// <summary>
        /// 当前显示的报工质检项目
        /// </summary>
        public WorkReportQualityItem? CurrentItem
        {
            get => _currentItem;
            set
            {
                SetProperty(ref _currentItem, value);
                UpdateCanSave();
            }
        }

        /// <summary>
        /// 是否可以保存
        /// </summary>
        public bool CanSave
        {
            get => _canSave;
            set => SetProperty(ref _canSave, value);
        }

        /// <summary>
        /// 是否正在保存
        /// </summary>
        public bool IsSaving
        {
            get => _isSaving;
            set
            {
                SetProperty(ref _isSaving, value);
                UpdateCanSave();
            }
        }

        /// <summary>
        /// 是否正在加载质检方案
        /// </summary>
        public bool IsLoadingPlans
        {
            get => _isLoadingPlans;
            set => SetProperty(ref _isLoadingPlans, value);
        }

        /// <summary>
        /// 是否全选
        /// </summary>
        public bool IsAllSelected
        {
            get => _isAllSelected;
            set
            {
                if (SetProperty(ref _isAllSelected, value))
                {
                    UpdateAllSelection(value);
                }
            }
        }

        /// <summary>
        /// 质检方案列表
        /// </summary>
        public ObservableCollection<QualityInspectionPlan> QualityInspectionPlans
        {
            get => _qualityInspectionPlans;
            set => SetProperty(ref _qualityInspectionPlans, value);
        }

        /// <summary>
        /// 返回命令
        /// </summary>
        public ICommand BackCommand { get; }

        /// <summary>
        /// 保存命令
        /// </summary>
        public ICommand SaveCommand { get; }

        /// <summary>
        /// 全选命令
        /// </summary>
        public ICommand SelectAllCommand { get; }

        /// <summary>
        /// 设置当前项目数据
        /// </summary>
        /// <param name="item">报工质检项目</param>
        public void SetCurrentItem(WorkReportQualityItem item)
        {
            CurrentItem = item;
        }

        /// <summary>
        /// 返回事件
        /// </summary>
        public event Action? BackRequested;

        /// <summary>
        /// 执行返回操作
        /// </summary>
        private void ExecuteBack()
        {
            // 触发页面导航事件，通知主窗口返回到列表页面
            RequestNavigateToPage?.Invoke("报工质检");
        }

        /// <summary>
        /// 加载质检方案列表
        /// </summary>
        private async Task LoadQualityInspectionPlansAsync()
        {
            try
            {
                IsLoadingPlans = true;

                var result = await _apiService.GetQualityInspectionPlansAsync();

                // 无论API成功还是失败，都会返回数据（失败时返回测试数据）
                if (result.Data != null)
                {
                    QualityInspectionPlans.Clear();
                    foreach (var plan in result.Data)
                    {
                        // 为每个方案添加选择状态变化监听
                        plan.PropertyChanged += Plan_PropertyChanged;
                        QualityInspectionPlans.Add(plan);
                    }

                    UpdateCanSave();
                }
            }
            catch (Exception ex)
            {
                // 即使发生异常，也不显示错误信息，因为ApiService会返回测试数据
                // 这里可以记录日志，但不影响用户体验
                System.Diagnostics.Debug.WriteLine($"加载质检方案时发生异常：{ex.Message}");
            }
            finally
            {
                IsLoadingPlans = false;
            }
        }

        /// <summary>
        /// 质检方案选择状态变化事件处理
        /// </summary>
        private void Plan_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(QualityInspectionPlan.IsSelected))
            {
                UpdateAllSelectedState();
                UpdateCanSave();
            }
        }

        /// <summary>
        /// 更新全选状态
        /// </summary>
        private void UpdateAllSelectedState()
        {
            if (QualityInspectionPlans.Count == 0)
            {
                _isAllSelected = false;
            }
            else
            {
                _isAllSelected = QualityInspectionPlans.All(p => p.IsSelected);
            }
            OnPropertyChanged(nameof(IsAllSelected));
        }

        /// <summary>
        /// 更新所有项目的选择状态
        /// </summary>
        private void UpdateAllSelection(bool isSelected)
        {
            foreach (var plan in QualityInspectionPlans)
            {
                plan.IsSelected = isSelected;
            }
        }

        /// <summary>
        /// 执行全选操作
        /// </summary>
        private void ExecuteSelectAll()
        {
            IsAllSelected = !IsAllSelected;
        }

        /// <summary>
        /// 执行保存操作
        /// </summary>
        private async Task ExecuteSaveAsync()
        {
            if (CurrentItem == null)
            {
                MessageBox.Show("没有可保存的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 获取选中的质检方案ID
            var selectedPlanIds = QualityInspectionPlans
                .Where(p => p.IsSelected)
                .Select(p => p.Id)
                .ToArray();

            if (selectedPlanIds.Length == 0)
            {
                MessageBox.Show("请至少选择一个质检方案", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                IsSaving = true;

                // 调用API，使用选中的质检方案ID
                var result = await _apiService.ProcessQualityInspectionAsync(
                    CurrentItem.Id ?? new Guid(),
                    selectedPlanIds);

                if (result.IsSuc && result.Data?.IsSuccess == true)
                {
                    // 保存成功
                    MessageBox.Show(
                        $"保存成功！\n" +
                        $"状态：{result.Data.Status}\n" +
                        $"处理时间：{result.Data.ProcessedAt:yyyy-MM-dd HH:mm:ss}\n" +
                        $"处理人：{result.Data.ProcessedBy}\n" +
                        $"添加关联数：{result.Data.AddedAssociationsCount}\n" +
                        $"选中方案数：{selectedPlanIds.Length}",
                        "保存成功",
                        MessageBoxButton.OK,
                        MessageBoxImage.Information);

                    // 更新当前项目状态
                    if (CurrentItem != null)
                    {
                        CurrentItem.Status = result.Data.Status;
                        OnPropertyChanged(nameof(CurrentItem));
                    }

                    // 通知质检列表页面刷新数据
                    TriggerQualityListRefresh();

                    // 可选：保存成功后返回列表页面
                    // RequestNavigateToPage?.Invoke("报工质检");
                }
                else
                {
                    // 保存失败
                    MessageBox.Show(
                        $"保存失败：{result.Msg}",
                        "保存失败",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    $"保存时发生异常：{ex.Message}",
                    "错误",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            finally
            {
                IsSaving = false;
            }
        }

        /// <summary>
        /// 更新是否可以保存的状态
        /// </summary>
        private void UpdateCanSave()
        {
            // 只有当前有数据、不在保存中且至少选择了一个质检方案时才能保存
            CanSave = CurrentItem != null && !IsSaving && QualityInspectionPlans.Any(p => p.IsSelected);
        }

        /// <summary>
        /// 触发质检列表页面刷新
        /// </summary>
        private void TriggerQualityListRefresh()
        {
            try
            {
                // 通过静态方法触发质检列表页面的数据刷新
                WorkReportQualityViewModel.TriggerRefreshData();
                System.Diagnostics.Debug.WriteLine("已触发质检列表页面数据刷新");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"触发质检列表刷新失败: {ex.Message}");
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // 清理事件监听
                foreach (var plan in QualityInspectionPlans)
                {
                    plan.PropertyChanged -= Plan_PropertyChanged;
                }

                // 清理资源
                CurrentItem = null;
                _apiService?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}